<template>
  <div class='container'>
    <el-dialog width="40%" :title="title" :visible="showSrticleDialog" @close="closeDialog">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
         <el-form-item label="文章标题" prop="title">
           <el-input v-model="ruleForm.title"></el-input>
         </el-form-item>
         <el-form-item label="文章内容" prop="articleBody" ref="editor">
           <!-- 富文本编辑器 -->
            <VueEditor @blur="handleBlur" :editor-toolbar="customToolbar" v-model="ruleForm.articleBody"/>
        </el-form-item>
        <el-form-item label="视频地址">
           <el-input v-model="ruleForm.videoURL"></el-input>
         </el-form-item>
      </el-form>
      <template #footer>
        <el-button size="small">取消</el-button>
        <el-button size="small" type="primary" @click="articleSubmit">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
// 引入富文本编辑器
import { VueEditor } from 'vue2-editor'
import { add, update } from '@/api/hmmm/articles.js'
export default {
  components: { VueEditor },
  props: {
    showSrticleDialog: {
      type: Boolean,
      required: true
    }
  },
  data () {
    return {
      title: '弹层标题',
      ruleForm: {
        title: '',
        articleBody: '',
        videoURL: ''
      },
      rules: {
        title: [{ required: true, message: '请输入文章标题', trigger: ['blur', 'change'] }],
        articleBody: [{ required: true, message: '请输入文章内容', trigger: ['blur', 'change'] }]
      },
      // 富文本编辑器的工具栏
      customToolbar: [
        ['bold', 'italic', 'underline'],
        ['strike'],
        [{ list: 'ordered' }, { list: 'bullet' }],
        ['blockquote'],
        ['code-block', 'image', 'link']
      ]
    }
  },
  methods: {
    closeDialog () {
      this.$emit('update:showSrticleDialog', false)
      this.$refs.ruleForm.resetFields()
      this.ruleForm = {
        title: '',
        articleBody: '',
        videoURL: ''
      }
    },
    // 富文本编辑器的blur方法---->为使得elementUi的表单校验在富文本编辑器中能正常使用
    handleBlur (v) {
      this.$refs.editor.$emit('el.form.blur', v)
    },
    articleSubmit () {
      this.$refs.ruleForm.validate(async boo => {
        if (!boo) return this.$message.error('请输入完整文章')
        if (this.title === '新增文章') {
          await add(this.ruleForm)
          this.$message.success('添加完成')
        }
        if (this.title === '编辑文章') {
          await update(this.ruleForm)
          this.$message.success('编辑完成')
        }
        // 关闭弹层---通知父组件重新获取数据
        this.closeDialog()
        this.$emit('getArticleList')
      })
    }
  }
}
</script>

<style scoped lang='scss'>
::v-deep .el-dialog__footer{
  text-align: right;
}
</style>
